package com.jn.erp.web.api.course.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jn.erp.utils.DateUtils;
import com.jn.erp.web.api.common.enums.ErrorEnum;
import com.jn.erp.web.api.course.entity.TCourseOrder;
import com.jn.erp.web.api.course.entity.TCourseOrderConfig;
import com.jn.erp.web.api.course.entity.TCourseOrderDetail;
import com.jn.erp.web.api.course.entity.THoliday;
import com.jn.erp.web.api.course.entity.dto.*;
import com.jn.erp.web.api.course.entity.vo.CourseTempVo;
import com.jn.erp.web.api.course.entity.vo.DataTrendsVo;
import com.jn.erp.web.api.course.entity.vo.TCourseOrderConfigVo;
import com.jn.erp.web.api.course.entity.vo.TCourseOrderVo;
import com.jn.erp.web.api.course.mapper.TCourseOrderConfigMapper;
import com.jn.erp.web.api.course.mapper.TCourseOrderDetailMapper;
import com.jn.erp.web.api.course.mapper.TCourseOrderMapper;
import com.jn.erp.web.api.course.mapper.THolidayMapper;
import com.jn.erp.web.api.course.service.TCourseOrderService;
import com.jn.erp.web.api.course.task.TCourseOrderTask;
import com.jn.erp.web.api.interaction.entity.TEvaluate;
import com.jn.erp.web.api.interaction.entity.TIntegral;
import com.jn.erp.web.api.interaction.entity.TIntegralConfig;
import com.jn.erp.web.api.interaction.mapper.TEvaluateMapper;
import com.jn.erp.web.api.interaction.mapper.TIntegralConfigMapper;
import com.jn.erp.web.api.interaction.mapper.TIntegralMapper;
import com.jn.erp.web.api.student.entity.Student;
import com.jn.erp.web.api.student.entity.StudentCourse;
import com.jn.erp.web.api.student.entity.TStudentClassRela;
import com.jn.erp.web.api.student.mapper.StudentMapper;
import com.jn.erp.web.api.student.mapper.TStudentClassRelaMapper;
import com.jn.erp.web.api.student.service.StudentCourseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wyp
 * @since 2024-09-04
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TCourseOrderServiceImpl extends ServiceImpl<TCourseOrderMapper, TCourseOrder> implements TCourseOrderService {

    @Autowired
    private TCourseOrderMapper tCourseOrderMapper;
    @Autowired
    private TCourseOrderConfigMapper tCourseOrderConfigMapper;
    @Autowired
    private StudentCourseService studentCourseService;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private TEvaluateMapper tEvaluateMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TCourseOrderTask tCourseOrderTask;

    @Autowired
    private TIntegralConfigMapper tIntegralConfigMapper;

    @Autowired
    private TIntegralMapper tIntegralMapper;

    @Autowired
    private TCourseOrderDetailMapper tCourseOrderDetailMapper;

    @Autowired
    private TStudentClassRelaMapper tStudentClassRelaMapper;

    @Autowired
    private THolidayMapper tHolidayMapper;
    @Override
    public TCourseOrder lastCourseOrder(LocalDateTime startTime, Long cofId,Long studentId) {
        return this.baseMapper.lastCourseOrder( startTime,cofId,studentId);
    }

    @Override
    public List<TCourseOrderDto> courseOrderList(TCourseOrderVo tCourseOrderVo) {
        if(StringUtils.isNotBlank(tCourseOrderVo.getOnlyThisWeek()) && "0".compareTo(tCourseOrderVo.getOnlyThisWeek()) == 0){
            tCourseOrderVo.setWeekStartTime(DateUtils.getMon().toString());
            tCourseOrderVo.setWeekEndTime(DateUtils.getMon().plusDays(6).toString());
        }

        List<TCourseOrderDto> tCourseOrderDtos = tCourseOrderMapper.courseOrderList(tCourseOrderVo);

        // 判断过没过期
        // 点没点完名
        // 试听过这节课的不能再试听

//        if(StringUtils.isNotBlank(tCourseOrderVo.getOnlyThisWeek()) && "0".compareTo(tCourseOrderVo.getOnlyThisWeek()) == 0){
//            tCourseOrderDtos = tCourseOrderDtos.stream().sorted(Comparator.comparing(TCourseOrderDto::getOrderNo)).collect(Collectors.toList());
//        }
        return tCourseOrderDtos;
    }

    @Override
    public List<StudentOrderListExcalDto> exportOrderList(TCourseOrderVo tCourseOrderVo) {
        List<StudentOrderListExcalDto> studentOrderListExcalDtos = tCourseOrderMapper.exportOrderList(tCourseOrderVo);
        return studentOrderListExcalDtos;
    }

    @Override
    public TCourseOrderDto getCourseOrderById(TCourseOrderVo tCourseOrderVo) {
        TCourseOrderDto  tCourseOrderDto = baseMapper.getCourseOrderById(tCourseOrderVo);
        if(!Objects.isNull(tCourseOrderDto) && !StringUtils.isEmpty(tCourseOrderDto.getAssistant())){
            String[] split = tCourseOrderDto.getAssistant().split(",");
            if(split.length > 0){
                List<Integer> collect = Arrays.stream(split).map(u -> {
                    return Integer.parseInt(u);
                }).collect(Collectors.toList());
                tCourseOrderDto.setAssistantArr(collect);
            }
        }

        return tCourseOrderDto;
    }

    @Override
    public List<TCourseOrderDto> orderStudentList(TCourseOrderVo tCourseOrderVo) {
        List<TCourseOrderDto> tCourseOrderDtos = baseMapper.orderStudentList(tCourseOrderVo);
        return tCourseOrderDtos;
    }

    @Override
    public List<TCourseOrderDto> orderListSecond(TCourseOrderVo tCourseOrderVo) {
        List<TCourseOrderDto> tCourseOrderDtos = baseMapper.orderListSecond(tCourseOrderVo);
        tCourseOrderDtos.stream().forEach(u->{
            if(u.getCompleted()==0 && u.getRepairState() == 1){
                u.setRepairStateStr("补课中");
            }
        });

        return tCourseOrderDtos;
    }

    @Override
    public String addStudent(TCourseOrderVo tCourseOrderVo) {
        List<CourseTempVo> ids = tCourseOrderVo.getIds();
        TCourseOrderConfig tCourseOrderConfig = tCourseOrderConfigMapper.selectById(tCourseOrderVo.getCofId());
        List<TCourseOrder> tCourseOrders = new ArrayList<>();
        ids.stream().forEach(u->{
            TCourseOrder courseOrder = new TCourseOrder(tCourseOrderConfig.getOrgId(), tCourseOrderConfig.getId(),tCourseOrderVo.getOrderNo(), 1, u.getCourseId(), tCourseOrderConfig.getClassId()
                    , tCourseOrderVo.getClassDate(), tCourseOrderConfig.getClassStartTime(), tCourseOrderConfig.getClassEndTime(), tCourseOrderConfig.getWeekNum(), u.getId()
                    , tCourseOrderConfig.getTeacher(), tCourseOrderConfig.getAssistant(), tCourseOrderConfig.getClassRoom(),tCourseOrderConfig.getDescription(), "1", tCourseOrderConfig.getClassHour(), 0, null, null
                    ,tCourseOrderVo.getTemp(),tCourseOrderVo.getTempOrderNo() ,LocalDateTime.now(), "sys", LocalDateTime.now(), "sys", "0");
            courseOrder.setType(1);
            if (tCourseOrderVo.getClassDates() != null) {
                LocalDateTime localDateTime = DateUtils.getLocalDateTime(tCourseOrderVo.getClassDates() + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
                courseOrder.setClassDate(localDateTime);
            }

            tCourseOrders.add(courseOrder);
        });
        this.saveBatch(tCourseOrders);
        return "S200";
    }

    @Override
    public List<StudentOrderListExcal2CDto> exportOrderListSecondC(TCourseOrderVo tCourseOrderVo) {
        List<StudentOrderListExcal2CDto> studentOrderListExcal2CDtos = tCourseOrderMapper.exportOrderListSecondC(tCourseOrderVo);
        return studentOrderListExcal2CDtos;
    }

    @Override
    public List<StudentOrderListExcal2SDto> exportOrderListSecondS(TCourseOrderVo tCourseOrderVo) {
        List<StudentOrderListExcal2SDto> studentOrderListExcal2SDtos = tCourseOrderMapper.exportOrderListSecondS(tCourseOrderVo);
        return studentOrderListExcal2SDtos;
    }

    @Override
    public String updateBatchOrder(List<TCourseOrder> tCourseOrders) {

//        boolean b = this.updateBatchById(tCourseOrders);
        for(TCourseOrder u :tCourseOrders){
            Student s = studentMapper.selectById(u.getStudentId());
            s.setStage(2);
            // 试听点名状态变成 已体验
            u.setType(u.getState());
            List<StudentCourse> studentCourses = studentCourseService.list(new QueryWrapper<StudentCourse>()
                    .eq("deleted","0").eq("exhausted",1).eq("student_id",u.getStudentId()).eq("course_id",u.getCourseId()).orderByAsc("level","id"));
//            点名迟到变更为在读，更改消费表的数据，
            if(!Objects.isNull(u.getClassHourPay())&& u.getClassHourPay()>0){
                studentMapper.update(s,new QueryWrapper<Student>().eq("id",u.getStudentId()));
              //                studentCourses =  studentCourses.stream().filter(i->i.getCountLessonComplete()<(i.getCountLessonTotal()-i.getCountLessonRefund())).collect(Collectors.toList());
                if(!CollectionUtils.isEmpty(studentCourses)  ){
                    TCourseOrder old = baseMapper.selectById(u.getId());
                    if(!Objects.isNull(old) && !Objects.isNull(old.getClassHourPay()) && 0 != old.getClassHourPay()){
                        StudentCourse studentCourse = studentCourseService.getById(old.getTscId());
                        studentCourse.setCountLessonComplete(studentCourse.getCountLessonComplete()-old.getClassHourPay());
                        studentCourseService.updateById(studentCourse);
                    }
                }else if(3 != u.getTemp()){
                    throw new RuntimeException( ErrorEnum.E103.getName()) ;
                }
                dealStudentCourse(u,studentCourses,"点名扣除");
            }else{
                TCourseOrder old = baseMapper.selectById(u.getId());
                if(!Objects.isNull(old)  && !Objects.isNull(old.getClassHourPay())  && 0 != old.getClassHourPay()){
                    StudentCourse studentCourse = studentCourseService.getById(old.getTscId());
                    studentCourse.setCountLessonComplete(studentCourse.getCountLessonComplete()-old.getClassHourPay());
                    studentCourseService.updateById(studentCourse);
                }
                dealStudentCourse(u,studentCourses,"点名扣除");
            }
            //添加评价信息
            TEvaluate tEvaluate = new TEvaluate(u.getOrgId(),u.getStudentId(),u.getOrderNo(),1,s.getName(),1,u.getState(),null,null,null,null,null,null,LocalDateTime.now(),u.getUpdateUser(),null,null,"0");
            QueryWrapper<TEvaluate> eq = new QueryWrapper<TEvaluate>().eq("org_id", tEvaluate.getOrgId()).eq("order_no", tEvaluate.getOrderNo()).eq("t_id", tEvaluate.gettId()).eq("is_delete", "0");
            List<TEvaluate> tEvaluates = tEvaluateMapper.selectList(eq);
            if(CollectionUtils.isEmpty(tEvaluates)){
                tEvaluateMapper.insert(tEvaluate);
            }else{
                tEvaluate.setState(null);
                tEvaluate.setCreateUser(null);
                tEvaluate.setCreateDate(null);
                tEvaluate.setUpdateUser(u.getUpdateUser());
                tEvaluate.setUpdateDate(LocalDateTime.now());
                tEvaluateMapper.update(tEvaluate,eq);
            }
            //添加积分
            TIntegralConfig t = tIntegralConfigMapper.selectOne(new QueryWrapper<TIntegralConfig>().eq("org_id", u.getOrgId()).eq("is_delete","0"));
            if(!Objects.isNull(t)&&(u.getState() ==2||u.getState() ==3)){
                TIntegral tIntegral = new TIntegral(u.getOrgId(),u.getStudentId(),t.getId(),2,t.getAttr2(),t.getName(),"点名",LocalDateTime.now(),u.getUpdateUser() ,null,null,"0");
                tIntegralMapper.insert(tIntegral);
            }
        }
        return "S200";
    }

    @Override
    public String updateOrderById(TCourseOrder tCourseOrder) {
        TCourseOrder old = baseMapper.selectById(tCourseOrder.getId());
        if(Objects.isNull(old.getTscId())){
            List<TCourseOrder> list = new ArrayList<>();
            old.setState(tCourseOrder.getState());
            old.setClassHourPay(tCourseOrder.getClassHourPay());
            old.setRemark(tCourseOrder.getRemark());
            list.add(old);
            return updateBatchOrder(list);
        }
        //标记已补直接处理，修改课次（上课记录）要进行课时处理
        if(!Objects.isNull(tCourseOrder.getState()) ){
            if(3 != old.getTemp()){
                StudentCourse studentCourse = studentCourseService.getById(old.getTscId());
                if(studentCourse.getExhausted() == 0){
                    throw new RuntimeException(ErrorEnum.E109.getName());
                }
                Integer countLessonComplete = 0;
                if(Objects.isNull(studentCourse)){
                    studentCourse= new StudentCourse();
                    countLessonComplete = 0;
                }else{
                    countLessonComplete = studentCourse.getCountLessonComplete() - old.getClassHourPay();
                }
                studentCourse.setCountLessonComplete(countLessonComplete);
                studentCourse.setEditor(Long.valueOf(tCourseOrder.getUpdateUser()));
                studentCourse.setEditTime(LocalDateTime.now());
                studentCourseService.updateById(studentCourse);
                List<StudentCourse> studentCourses = studentCourseService.list(new QueryWrapper<StudentCourse>()
                        .eq("deleted","0").eq("exhausted",1).eq("student_id",old.getStudentId()).eq("course_id",old.getCourseId()).orderByAsc("level","id"));
                BigDecimal amount = new BigDecimal(0);
                if(0 != studentCourse.getCountLessonTotalNormal()){
                    amount = studentCourse.getDiscountAmount().divide(new BigDecimal(studentCourse.getCountLessonTotalNormal()),4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(-old.getClassHourPayNormal()));
                }
                TCourseOrderDetail tCourseOrderDetail = new TCourseOrderDetail(old.getOrgId(),old.getOrderNo(),studentCourse.getOrderNo(),2,-old.getClassHourPay(),-old.getClassHourPayNormal(),old.getClassHourPayNormal() -old.getClassHourPay(),amount,"修改点名回退",LocalDateTime.now(),tCourseOrder.getUpdateUser(),null,null,"0");
                tCourseOrderDetailMapper.insert(tCourseOrderDetail);
                int i = baseMapper.updateById(tCourseOrder);
                TCourseOrder n = baseMapper.selectById(tCourseOrder.getId());
                n.setClassHourPayNormal(0);
                // 试听学员状态
                n.setType(tCourseOrder.getState());
                dealStudentCourse(n,studentCourses,"修改点名扣除");
            }else{
                if(tCourseOrder.getClassHourPay() != 0 ){
                    throw new RuntimeException(ErrorEnum.E108.getName()) ;
                }

                int i = baseMapper.updateById(tCourseOrder);
            }
            //积分处理
            if(old.getState()==2||old.getState()==3 ){
                if(tCourseOrder.getState()==4||tCourseOrder.getState()==5){
                    //添加积分
                    TIntegralConfig t = tIntegralConfigMapper.selectOne(new QueryWrapper<TIntegralConfig>().eq("org_id", old.getOrgId()).eq("is_delete","0"));
                    if(!Objects.isNull(t)){
                        TIntegral tIntegral = new TIntegral(old.getOrgId(),old.getStudentId(),t.getId(),2,-t.getAttr2(),t.getName(),"修改点名回退",LocalDateTime.now(),String.valueOf(tCourseOrder.getUpdateUser()) ,null,null,"0");
                        tIntegralMapper.insert(tIntegral);
                    }
                }
            }else{
                if(tCourseOrder.getState()==2||tCourseOrder.getState()==3){
                    //添加积分
                    TIntegralConfig t = tIntegralConfigMapper.selectOne(new QueryWrapper<TIntegralConfig>().eq("org_id", old.getOrgId()).eq("is_delete","0"));
                    if(!Objects.isNull(t)){
                        TIntegral tIntegral = new TIntegral(old.getOrgId(),old.getStudentId(),t.getId(),2,t.getAttr2(),t.getName(),"修改点名",LocalDateTime.now(),String.valueOf(tCourseOrder.getUpdateUser()) ,null,null,"0");
                        tIntegralMapper.insert(tIntegral);
                    }
                }
            }
        }else{
            int i = baseMapper.updateById(tCourseOrder);
        }

        return ErrorEnum.S200.getName();
    }

    private void dealStudentCourse(TCourseOrder t ,List<StudentCourse> studentCourses,String source){

        Integer temp =t.getClassHourPay();
        Boolean flag = true;
        for( int i = 0 ; i < studentCourses.size() ; i++){
            StudentCourse s = studentCourses.get(i);
//                扣除课时类型0正常课时1赠送课时2复合扣课时

            if (temp <= s.getCountLessonTotalNormal() - s.getCountLessonComplete()) {
                s.setCountLessonComplete(s.getCountLessonComplete() + temp);

                studentCourseService.updateById(s);
                t.setTscId(s.getId());
                t.setClassHourPayNormal(temp);
                t.setClassHourPayType("0");
                flag = false;
                BigDecimal amount = new BigDecimal(0);
                if(0 != s.getCountLessonTotalNormal()){
                    amount = s.getDiscountAmount().divide(new BigDecimal(s.getCountLessonTotalNormal()),4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(temp));
                }
                TCourseOrderDetail tCourseOrderDetail = new TCourseOrderDetail(t.getOrgId(),t.getOrderNo(),s.getOrderNo(),1,temp,temp,0,amount,source,LocalDateTime.now(),t.getUpdateUser(),null,null,"0");
                tCourseOrderDetailMapper.insert(tCourseOrderDetail);
                break;
            } else if ( s.getCountLessonTotalNormal() - s.getCountLessonComplete() >0 && temp <= s.getCountLessonTotal() - s.getCountLessonComplete()) {
                Integer classHourPayNormal = s.getCountLessonTotalNormal() - s.getCountLessonComplete();
                t.setClassHourPayNormal(classHourPayNormal);
                s.setCountLessonComplete(s.getCountLessonComplete() + temp);
                studentCourseService.updateById(s);
                t.setTscId(s.getId());
                t.setClassHourPayType("2");
                flag = false;
                BigDecimal amount = new BigDecimal(0);
                if(0 != s.getCountLessonTotalNormal()){
                    amount = s.getDiscountAmount().divide(new BigDecimal(s.getCountLessonTotalNormal()),4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(classHourPayNormal));
                }
                TCourseOrderDetail tCourseOrderDetail = new TCourseOrderDetail(t.getOrgId(),t.getOrderNo(),s.getOrderNo(),1,temp,classHourPayNormal,temp - classHourPayNormal,amount,source,LocalDateTime.now(),t.getUpdateUser(),null,null,"0");
                tCourseOrderDetailMapper.insert(tCourseOrderDetail);
                break;
            } else if (temp <= s.getCountLessonTotal() - s.getCountLessonComplete()) {
                s.setCountLessonComplete(s.getCountLessonComplete() + temp);
                studentCourseService.updateById(s);
                t.setTscId(s.getId());
                t.setClassHourPayType("1");
                flag = false;
                BigDecimal amount = new BigDecimal(0);
                if(0 != s.getCountLessonTotalNormal()){
                    amount = s.getDiscountAmount().divide(new BigDecimal(s.getCountLessonTotalNormal()),4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(0));
                }
                TCourseOrderDetail tCourseOrderDetail = new TCourseOrderDetail(t.getOrgId(),t.getOrderNo(),s.getOrderNo(),1,temp,0,temp,amount,source,LocalDateTime.now(),t.getUpdateUser(),null,null,"0");
                tCourseOrderDetailMapper.insert(tCourseOrderDetail);
                break;
            }else  if(i == studentCourses.size() -1) {
                if(s.getCountLessonTotalNormal() - s.getCountLessonComplete() >0){
                    Integer classHourPayNormal = temp - s.getCountLessonTotalGive();
                    s.setCountLessonComplete(s.getCountLessonComplete() + temp);
                    studentCourseService.updateById(s);
                    t.setTscId(s.getId());
                    t.setClassHourPayNormal(classHourPayNormal);
                    t.setClassHourPayType("3");
                    flag = false;
                    BigDecimal amount = new BigDecimal(0);
                    if(0 != s.getCountLessonTotalNormal()){
                        amount = s.getDiscountAmount().divide(new BigDecimal(s.getCountLessonTotalNormal()),4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(classHourPayNormal));
                    }
                    TCourseOrderDetail tCourseOrderDetail = new TCourseOrderDetail(t.getOrgId(),t.getOrderNo(),s.getOrderNo(),1,temp,classHourPayNormal,s.getCountLessonTotalGive(),amount,source,LocalDateTime.now(),t.getUpdateUser(),null,null,"0");
                    tCourseOrderDetailMapper.insert(tCourseOrderDetail);
                }else if(s.getCountLessonTotal() - s.getCountLessonComplete() >0){
                    Integer classHourPayNormal = temp  - (s.getCountLessonTotal() - s.getCountLessonComplete());
                    s.setCountLessonComplete(s.getCountLessonComplete() + temp);
                    studentCourseService.updateById(s);
                    t.setTscId(s.getId());
                    t.setClassHourPayNormal(classHourPayNormal);
                    t.setClassHourPayType("4");
                    flag = false;
                    BigDecimal amount = new BigDecimal(0);
                    if(0 != s.getCountLessonTotalNormal()){
                        amount = s.getDiscountAmount().divide(new BigDecimal(s.getCountLessonTotalNormal()),4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(classHourPayNormal));
                    }
                    TCourseOrderDetail tCourseOrderDetail = new TCourseOrderDetail(t.getOrgId(),t.getOrderNo(),s.getOrderNo(),1,temp,classHourPayNormal,s.getCountLessonTotal() - s.getCountLessonComplete(),amount,source,LocalDateTime.now(),t.getUpdateUser(),null,null,"0");
                    tCourseOrderDetailMapper.insert(tCourseOrderDetail);
                }else{
                    Integer classHourPayNormal = temp;
                    s.setCountLessonComplete(s.getCountLessonComplete() + temp);
                    studentCourseService.updateById(s);
                    t.setTscId(s.getId());
                    t.setClassHourPayNormal(classHourPayNormal);
                    t.setClassHourPayType("5");
                    flag = false;
                    BigDecimal amount = new BigDecimal(0);
                    if(0 != s.getCountLessonTotalNormal()){
                        amount = s.getDiscountAmount().divide(new BigDecimal(s.getCountLessonTotalNormal()),4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(classHourPayNormal));
                    }
                    TCourseOrderDetail tCourseOrderDetail = new TCourseOrderDetail(t.getOrgId(),t.getOrderNo(),s.getOrderNo(),1,temp,classHourPayNormal,0,amount,source,LocalDateTime.now(),t.getUpdateUser(),null,null,"0");
                    tCourseOrderDetailMapper.insert(tCourseOrderDetail);
                }
                break;
            }
        }

        if(flag && 3 != t.getTemp()){
            throw new RuntimeException(ErrorEnum.E107.getName());
        }

        boolean b = this.updateById(t);
    }
    @Override
    public String saveRepair(TCourseOrderConfigVo tCourseOrderConfigVo) {
        //可能存在Redis容灾不生效的的情况取数据库数据进行初始化
        tCourseOrderTask.initOrderNo();

        tCourseOrderConfigVo.setType(2);
        tCourseOrderConfigVo.setState(1);
        tCourseOrderConfigMapper.insert(tCourseOrderConfigVo);
        List<TCourseOrder> tCourseOrders = tCourseOrderConfigVo.gettCourseOrders();
        List<TCourseOrder> list = new ArrayList<>();
        tCourseOrders.stream().forEach(u->{
            Student s = studentMapper.selectById(u.getStudentId());
//            LocalDateTime classDate = DateUtils.getLocalDateTime(tCourseOrderConfigVo.getClassDate(), "yyyy-MM-dd'T'HH:mm:ss.SSS");
            LocalDateTime classDate = DateUtils.getLocalDateTime(tCourseOrderConfigVo.getClassDate(), "yyyy-MM-dd HH:mm:ss");
            String orderNo =tCourseOrderTask.getOrderNo(classDate,"courseOrderNo",tCourseOrderConfigVo.getId());
            u.setCreateDate(LocalDateTime.now());
            u = new TCourseOrder(tCourseOrderConfigVo.getOrgId(), tCourseOrderConfigVo.getId(),orderNo, u.getState(),Objects.isNull(u.getCourseId())? tCourseOrderConfigVo.getCourseId():u.getCourseId(), tCourseOrderConfigVo.getClassId()
                    , classDate, tCourseOrderConfigVo.getClassStartTime(), tCourseOrderConfigVo.getClassEndTime(), tCourseOrderConfigVo.getWeekNum(), u.getStudentId()
                    , tCourseOrderConfigVo.getTeacher(), tCourseOrderConfigVo.getAssistant(), tCourseOrderConfigVo.getClassRoom(),tCourseOrderConfigVo.getDescription(), "1", tCourseOrderConfigVo.getClassHour(), u.getClassHourPay(), LocalDateTime.now(), u.getRemark()
                    ,2,u.getTempOrderNo() ,LocalDateTime.now(), "sys", LocalDateTime.now(), "sys", "0");
            list.add(u);
           //处理学生学时
            List<StudentCourse> studentCourses = studentCourseService.list(new QueryWrapper<StudentCourse>()
                    .eq("deleted","0").eq("exhausted",1).eq("student_id",u.getStudentId()).eq("course_id",u.getCourseId()).orderByAsc("level","id"));
            if(!CollectionUtils.isEmpty(studentCourses)){
                dealStudentCourse(u,studentCourses,"点名扣除-补课");
            }else{
                throw new RuntimeException( ErrorEnum.E103.getName()) ;
            }
            //添加评价信息
            TEvaluate tEvaluate = new TEvaluate(u.getOrgId(),u.getStudentId(),u.getOrderNo(),1,s.getName(),1,u.getState(),null,null,null,null,null,null,LocalDateTime.now(),u.getUpdateUser(),null,null,"0");
            tEvaluateMapper.insert(tEvaluate);
        });
        this.saveBatch(list);

        return "S200";
    }

    @Override
    public List<TCourseOrderDto> repairDetail(TCourseOrderVo tCourseOrderVo) {
        List<TCourseOrderDto> tCourseOrders = baseMapper.repairDetail(tCourseOrderVo);
        return tCourseOrders;
    }

    @Override
    public List<TCourseOrderDto> orderListThird(TCourseOrderVo tCourseOrderVo) {
        List<TCourseOrderDto> tCourseOrderDtos = baseMapper.orderListThird(tCourseOrderVo);
        return tCourseOrderDtos;
    }

    @Override
    public TCourseOrderDto orderDetailSecond(TCourseOrderVo tCourseOrderVo) {
        TCourseOrderDto tCourseOrderDto = baseMapper.orderDetailSecond(tCourseOrderVo);
        return tCourseOrderDto;
    }

    @Override
    public Map orderCountSecond(TCourseOrderVo tCourseOrderVo) {
        Map map = baseMapper.orderCountSecond(tCourseOrderVo);
        return map;
    }

    @Override
    public int called(String orderNo) {
        int i = baseMapper.called(orderNo);
        return i;
    }

    @Override
    public List<TCourseOrderDto> orderFilterList(TCourseOrderVo tCourseOrderVo) {
        if(StringUtils.isNotBlank(tCourseOrderVo.getOnlyThisWeek()) && "0".compareTo(tCourseOrderVo.getOnlyThisWeek()) == 0){
            tCourseOrderVo.setWeekStartTime(DateUtils.getMon().toString());
            tCourseOrderVo.setWeekEndTime(DateUtils.getMon().plusDays(6).toString());
        }
        List<TCourseOrderDto> tCourseOrderDtos = tCourseOrderMapper.courseOrderLists(tCourseOrderVo);
        if(StringUtils.isNotBlank(tCourseOrderVo.getOnlyThisWeek()) && "0".compareTo(tCourseOrderVo.getOnlyThisWeek()) == 0){
            tCourseOrderDtos = tCourseOrderDtos.stream().sorted(Comparator.comparing(TCourseOrderDto::getOrderNo)).collect(Collectors.toList());
        }
        return tCourseOrderDtos;
    }

    @Override
    public String getMaxOrderNo(String date) {
        String orderNo = baseMapper.getMaxOrderNo(date);
        return orderNo;
    }


    @Override
    public Map countAcademicData(DataTrendsVo dataTrendsVo){
        Map result = new HashMap();
        if(2==dataTrendsVo.getType()){
            dataTrendsVo.setStartDateMonth(dataTrendsVo.getStartDate());
            dataTrendsVo.setEndDateMonth(dataTrendsVo.getEndDate());
            dataTrendsVo.setStartDate(dataTrendsVo.getStartDate()+"-01");
            try {
                dataTrendsVo.setEndDate(DateUtils.getEndDayByMonth(dataTrendsVo.getEndDate()));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        //环比获取上礼拜,周比获取去年
        try {
            String lastWeek = "";
            String lastYear = "";
            String lastStartWeek  = "";
            String lastStartYear = "";
            if(1==dataTrendsVo.getType()){
                lastWeek = DateUtils.getLastDay(dataTrendsVo.getEndDate(), -1);
                lastYear = DateUtils.getLastDay(dataTrendsVo.getEndDate(), -7);
                lastStartWeek  = DateUtils.getLastDay(dataTrendsVo.getStartDate(), -1);
                lastStartYear = DateUtils.getLastDay(dataTrendsVo.getStartDate(), -7);
            }else if(2==dataTrendsVo.getType()){
                lastWeek = DateUtils.getEndDayByMonth(DateUtils.getLastMonth(dataTrendsVo.getEndDate(),1));
                lastYear = DateUtils.getLastYear(dataTrendsVo.getEndDate(), -1);
                lastStartWeek  = DateUtils.getLastMonth(dataTrendsVo.getStartDate(),1) + "-01";
                lastStartYear = DateUtils.getLastYear(dataTrendsVo.getStartDate(), -1);
            }

            dataTrendsVo.setEndDateLastWeek(lastWeek);
            dataTrendsVo.setEndDateLastYear(lastYear);
            //老师出勤率
            BigDecimal attendance = attendance(dataTrendsVo, dataTrendsVo.getStartDate(), dataTrendsVo.getEndDate(),result,"classHour", "specifyNumber", "studentAttendance","totalNum");
            BigDecimal attendanceWeek = attendance(dataTrendsVo, lastStartWeek, lastWeek,result,"classHourWeek", "specifyNumberWeek", "studentAttendanceWeek","totalNum");
            BigDecimal attendanceYear = attendance(dataTrendsVo, lastStartYear , lastYear,result,"classHourYear", "specifyNumberYear", "studentAttendanceYear","totalNum");
            result.put("attendance",attendance);
            result.put("attendanceWeek",attendanceWeek);
            result.put("attendanceYear",attendanceYear);
            //授课课时
            Map<String,BigDecimal> actualNumberMap = baseMapper.count(dataTrendsVo,dataTrendsVo.getStartDate(),dataTrendsVo.getEndDate());
            Map<String,BigDecimal> actualNumberMapWeek = baseMapper.count(dataTrendsVo,lastStartWeek, dataTrendsVo.getEndDate());
            Map<String,BigDecimal> actualNumberMapYear = baseMapper.count(dataTrendsVo,lastStartYear , dataTrendsVo.getEndDate());
            result.put("actualNumber",actualNumberMap.get("actualNumber"));
            result.put("actualNumberWeek",actualNumberMapWeek.get("actualNumber"));
            result.put("actualNumberYear",actualNumberMapYear.get("actualNumber"));
            //课消金额
            Map<String,BigDecimal> consumptionMap = baseMapper.courseConsumption(dataTrendsVo,dataTrendsVo.getStartDate(),dataTrendsVo.getEndDate(),"'%Y-%m-%d'");
            Map<String,BigDecimal> consumptionMapWeek = baseMapper.courseConsumption(dataTrendsVo,lastStartWeek, dataTrendsVo.getEndDate(),"'%Y-%m-%d'");
            Map<String,BigDecimal> consumptionMapYear = baseMapper.courseConsumption(dataTrendsVo,lastStartYear , dataTrendsVo.getEndDate(),"'%Y-%m-%d'");
            result.put("consumption",consumptionMap.get("amount"));
            result.put("consumptionWeek",consumptionMapWeek.get("amount"));
            result.put("consumptionYear",consumptionMapYear.get("amount"));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        //在读学员数
        Map map = studentMapper.countAcademicData(dataTrendsVo);
        result.putAll(map);
        return result;
    }

    @Override
    public  Map<String, List<List>> dataTrendsEChart(DataTrendsVo dataTrendsVo) {
        List<DataTrendsDto> list = dataTrends( dataTrendsVo);
        Map<String, List<List>> result = new HashMap<>();
        List<List> numList = new ArrayList<>();
        List<List> totalNumList = new ArrayList<>();
        List<List>  callNumList = new ArrayList<>();
        List<List>  repairNumList = new ArrayList<>();
        List<List> callOrderNumList = new ArrayList<>();
        List<List>  classHourList = new ArrayList<>();
        List<List>  classHourPayList = new ArrayList<>();
        List<List>  amountList = new ArrayList<>();
        List<List>  specifyNumberList = new ArrayList<>();
        for(DataTrendsDto dto : list){
            String date = dto.getDateValue();
            List num = new ArrayList<>();
            List totalNum = new ArrayList<>();
            List callNum = new ArrayList<>();
            List repairNum = new ArrayList<>();
            List callOrderNum = new ArrayList<>();
            List classHour = new ArrayList<>();
            List classHourPay = new ArrayList<>();
            List amount = new ArrayList();
            List specifyNumber = new ArrayList();
            num.add(date);
            num.add(new BigDecimal(dto.getNum()) );
            numList.add(num);

            totalNum.add(date);
            totalNum.add( new BigDecimal(dto.getTotalNum()));
            totalNumList.add(totalNum);
            callNum.add(date);
            callNum.add(new BigDecimal(dto.getCallNum()));
            callNumList.add(callNum);
            repairNum.add(date);
            repairNum.add(new BigDecimal(dto.getRepairNum()));
            repairNumList.add(repairNum);
            callOrderNum.add(date);
            callOrderNum.add(new BigDecimal(dto.getCallOrderNum()));
            callOrderNumList.add(callOrderNum);
            classHour.add(date);
            classHour.add(new BigDecimal(dto.getClassHour()));
            classHourList.add(classHour);
            classHourPay.add(date);
            classHourPay.add(new BigDecimal(dto.getClassHourPay()));
            classHourPayList.add(classHourPay);
            amount.add(date);
            amount.add(new BigDecimal(dto.getAmount()));
            amountList.add(amount);
            specifyNumber.add(date);
            specifyNumber.add(new BigDecimal(dto.getSpecifyNumber()));
            specifyNumberList.add(specifyNumber);
        }
        result.put("numList",numList);
        result.put("totalNumList",totalNumList);
        result.put("callNumList",callNumList);
        result.put("repairNumList",repairNumList);
        result.put("callOrderNumList",callOrderNumList);
        result.put("classHourList",classHourList);
        result.put("classHourPayList",classHourPayList);
        result.put("amountList",amountList);
        result.put("specifyNumberList",specifyNumberList);
        return result;
    }

    @Override
    public List<DataTrendsDto> dataTrends(DataTrendsVo dataTrendsVo){
        List<DataTrendsDto> list = new ArrayList<>();
        switch (dataTrendsVo.getType()) {
            case 1: {
                list = baseMapper.dataTrends(dataTrendsVo);
                //出勤率
                list.stream().forEach(u->{
                    Map map = new HashMap();
                    BigDecimal attendance = attendance(dataTrendsVo, u.getDateValue(), u.getDateValue(),map,"classHour", "specifyNumber", "studentAttendance","totalNum");
                    u.setAttendance(attendance.toString());
                    u.setStudentAttendance(map.get("studentAttendance").toString());
                    u.setSpecifyNumber(map.get("specifyNumber").toString());
                    u.setTotalNum(map.get("totalNum").toString());
                    Map<String, Long> studentStudying = baseMapper.countStudentStudying(dataTrendsVo, "'%Y-%m-%d'",u.getDateValue());
                    u.setNum(studentStudying.get("num").toString());
                    Map<String,BigDecimal> consumptionMap = baseMapper.courseConsumption(dataTrendsVo,u.getDateValue(),u.getDateValue(),"'%Y-%m-%d'");
                    u.setAmount(consumptionMap.get("amount").toString());
                });
                break;
            }
            case 2: {
                dataTrendsVo.setStartDateMonth(dataTrendsVo.getStartDate());
                dataTrendsVo.setEndDateMonth(dataTrendsVo.getEndDate());
                dataTrendsVo.setStartDate(dataTrendsVo.getStartDate()+"-01");
                try {
                    dataTrendsVo.setEndDate(DateUtils.getEndDayByMonth(dataTrendsVo.getEndDate()));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                list = baseMapper.dataTrendsMonth(dataTrendsVo);
                //出勤率
                list.stream().forEach(u->{
                    try {
                        Map map = new HashMap();
                        BigDecimal attendance = attendance(dataTrendsVo, u.getDateValue()+"-01", DateUtils.getEndDayByMonth(u.getDateValue()),map,"classHour", "specifyNumber", "studentAttendance","totalNum");
                        u.setAttendance(attendance.toString());
                        u.setStudentAttendance(map.get("studentAttendance").toString());
                        u.setSpecifyNumber(map.get("specifyNumber").toString());
                        u.setTotalNum(map.get("totalNum").toString());
                        Map<String, Long> studentStudying = baseMapper.countStudentStudying(dataTrendsVo, "'%Y-%m'",u.getDateValue());
                        u.setNum(studentStudying.get("num").toString());
                        Map<String,BigDecimal> consumptionMap = baseMapper.courseConsumption(dataTrendsVo,u.getDateValue(),u.getDateValue(),"'%Y-%m'");
                        u.setAmount(consumptionMap.get("amount").toString());
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                });
                break;
            }
        }
        list.stream().forEach(u->{
            DecimalFormat decimalFormat = new DecimalFormat("0.##");
            u.setAttendance( decimalFormat.format(new BigDecimal(u.getAttendance()).multiply(new BigDecimal(100))).toString()+"%");
            u.setStudentAttendance( decimalFormat.format(new BigDecimal(u.getStudentAttendance()).multiply(new BigDecimal(100))).toString()+"%");
        });
        return list;
    }

    @Override
    public List<DataTrendsDto> dataTrendsTeacher(DataTrendsVo dataTrendsVo) {
        if(2==dataTrendsVo.getType()){
            dataTrendsVo.setStartDateMonth(dataTrendsVo.getStartDate());
            dataTrendsVo.setEndDateMonth(dataTrendsVo.getEndDate());
            dataTrendsVo.setStartDate(dataTrendsVo.getStartDate()+"-01");
            try {
                dataTrendsVo.setEndDate(DateUtils.getEndDayByMonth(dataTrendsVo.getEndDate()));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        List<DataTrendsDto> list = baseMapper.dataTrendsTeacher(dataTrendsVo);
        //出勤率
        list.stream().forEach(u->{
            dataTrendsVo.setTeacher(Long.parseLong(u.getId()));

            Map map = new HashMap();
            BigDecimal attendance = attendance(dataTrendsVo, dataTrendsVo.getStartDate(), dataTrendsVo.getEndDate(),map,"classHour", "specifyNumber", "studentAttendance","totalNum");
            u.setAttendance(attendance.toString());
            u.setStudentAttendance(map.get("studentAttendance").toString());
            u.setSpecifyNumber(map.get("specifyNumber").toString());
            u.setTotalNum(map.get("totalNum").toString());
            DecimalFormat decimalFormat = new DecimalFormat("0.##");
            u.setAttendance( decimalFormat.format(attendance.multiply(new BigDecimal(100))).toString()+"%");
            u.setStudentAttendance( decimalFormat.format(new BigDecimal(u.getStudentAttendance()).multiply(new BigDecimal(100))).toString()+"%");
        });

        return list;
    }

    @Override
    public List<DataTrendsDto> dataTrendsClass(DataTrendsVo dataTrendsVo)  {
        if(2==dataTrendsVo.getType()){
            dataTrendsVo.setStartDateMonth(dataTrendsVo.getStartDate());
            dataTrendsVo.setEndDateMonth(dataTrendsVo.getEndDate());
            dataTrendsVo.setStartDate(dataTrendsVo.getStartDate()+"-01");
            try {
                dataTrendsVo.setEndDate(DateUtils.getEndDayByMonth(dataTrendsVo.getEndDate()));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        List<DataTrendsDto> list = baseMapper.dataTrendsClass(dataTrendsVo);
        //出勤率
        list.stream().forEach(u->{
            dataTrendsVo.setClassId(Long.parseLong(u.getId()));

            Map map = new HashMap();
            BigDecimal attendance = attendance(dataTrendsVo, dataTrendsVo.getStartDate(), dataTrendsVo.getEndDate(),map,"classHour", "specifyNumber", "studentAttendance","totalNum");
            u.setAttendance(attendance.toString());
            u.setStudentAttendance(map.get("studentAttendance").toString());
            u.setSpecifyNumber(map.get("specifyNumber").toString());
            u.setTotalNum(map.get("totalNum").toString());
            DecimalFormat decimalFormat = new DecimalFormat("0.##");
            u.setAttendance( decimalFormat.format(attendance.multiply(new BigDecimal(100))).toString()+"%");
            u.setStudentAttendance( decimalFormat.format(new BigDecimal(u.getStudentAttendance()).multiply(new BigDecimal(100))).toString()+"%");
        });
        return list;
    }

    @Override
    public List<DataTrendsDto> dataTrendCourse(DataTrendsVo dataTrendsVo){
        if(2==dataTrendsVo.getType()){
            dataTrendsVo.setStartDateMonth(dataTrendsVo.getStartDate());
            dataTrendsVo.setEndDateMonth(dataTrendsVo.getEndDate());
            dataTrendsVo.setStartDate(dataTrendsVo.getStartDate()+"-01");
            try {
                dataTrendsVo.setEndDate(DateUtils.getEndDayByMonth(dataTrendsVo.getEndDate()));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        List<DataTrendsDto> list = baseMapper.dataTrendCourse(dataTrendsVo);
        //出勤率
        list.stream().forEach(u->{
            dataTrendsVo.setCourseId(Long.parseLong(u.getId()));

            Map map = new HashMap();
            BigDecimal attendance = attendance(dataTrendsVo, dataTrendsVo.getStartDate(), dataTrendsVo.getEndDate(),map,"classHour", "specifyNumber", "studentAttendance","totalNum");
            u.setAttendance(attendance.toString());
            u.setStudentAttendance(map.get("studentAttendance").toString());
            u.setSpecifyNumber(map.get("specifyNumber").toString());
            u.setTotalNum(map.get("totalNum").toString());
            DecimalFormat decimalFormat = new DecimalFormat("0.##");
            u.setAttendance( decimalFormat.format(attendance.multiply(new BigDecimal(100))).toString()+"%");
            u.setStudentAttendance( decimalFormat.format(new BigDecimal(u.getStudentAttendance()).multiply(new BigDecimal(100))).toString()+"%");
            Map<String,BigDecimal> consumptionMap = baseMapper.courseConsumption(dataTrendsVo,dataTrendsVo.getStartDate(), dataTrendsVo.getEndDate(),"'%Y-%m-%d'");
            u.setAmount(consumptionMap.get("amount").toString());
        });
        return list;
    }

    @Override
    public List<DataTrendsDto> dataTrendStudent(DataTrendsVo dataTrendsVo) {
        if(2==dataTrendsVo.getType()){
            dataTrendsVo.setStartDateMonth(dataTrendsVo.getStartDate());
            dataTrendsVo.setEndDateMonth(dataTrendsVo.getEndDate());
            dataTrendsVo.setStartDate(dataTrendsVo.getStartDate()+"-01");
            try {
                dataTrendsVo.setEndDate(DateUtils.getEndDayByMonth(dataTrendsVo.getEndDate()));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        List<DataTrendsDto> list = baseMapper.dataTrendStudent(dataTrendsVo);
//        //出勤率
//        list.stream().forEach(u->{
//            BigDecimal attendance = attendance(dataTrendsVo, dataTrendsVo.getStartDate(), dataTrendsVo.getEndDate());
//             DecimalFormat decimalFormat = new DecimalFormat("0.##");
//            u.setAttendance( decimalFormat.format(attendance.multiply(new BigDecimal(100))).toString()+"%");
//        });
        return list;
    }

    @Override
    public Long getUserIdIncompleteCount(TCourseOrderVo tCourseOrderVo) {
        return baseMapper.getUserIdIncompleteCount(tCourseOrderVo);
    }

    private BigDecimal attendance(DataTrendsVo dataTrendsVo,String lastStartDate,String endTime,Map map,String classHourStr,String specifyNumberStr,String studentAttendanceStr,String totalNumStr){
        //排课数
        Integer specifyNumber = 0;
        //上课数
        BigDecimal actualNumber = new BigDecimal(0);
        //出勤率
        BigDecimal  attendance = new BigDecimal(0);

        List<TCourseOrderConfig> tCourseOrderConfigs = tCourseOrderConfigMapper.selectList(
                new QueryWrapper<TCourseOrderConfig>().eq("is_delete", 0).eq("excess", 1).eq("org_id", dataTrendsVo.getOrgId())
                        .and(qw->qw.between("DATE_FORMAT(start_time, '%Y-%m-%d' )",lastStartDate,endTime).or().between("DATE_FORMAT(end_time, '%Y-%m-%d' )",lastStartDate,endTime)
                                .or(qw2->qw2.le("DATE_FORMAT(start_time, '%Y-%m-%d' )",lastStartDate).ge("DATE_FORMAT(end_time, '%Y-%m-%d' )",endTime)))
                        .eq(!Objects.isNull(dataTrendsVo.getClassId()),"class_id",dataTrendsVo.getClassId()).eq(!Objects.isNull(dataTrendsVo.getCourseId()),"course_id",dataTrendsVo.getCourseId())
                        .eq(!Objects.isNull(dataTrendsVo.getTeacher()),"teacher",dataTrendsVo.getTeacher()));
        Integer roundTotal = 0;
        if(!CollectionUtils.isEmpty(tCourseOrderConfigs)){
            for (TCourseOrderConfig tCourseOrderConfig : tCourseOrderConfigs){
                String stratD = "1900-01-01";
                String endD = "2555-01-01";
                Integer round = 0;
                if(Objects.isNull(tCourseOrderConfig.getStartTime())){
                    round= 0;
                }else{
                    String startDateC = tCourseOrderConfig.getStartTime().substring(0, 10);

                    if(startDateC.compareTo(endTime)>0){
                        round= 0;
                    }else{
                        String startDate = "";
                        if(startDateC.compareTo(lastStartDate)<0){
                            startDate = lastStartDate;
                        }else {
                            startDate = startDateC;
                        }
                        if(endTime.compareTo(startDateC)<0){
                            round= 0;
                        }else{
                            String endDate = "";
                            if(Objects.isNull(tCourseOrderConfig.getEndTime())){
                                endDate = endTime;
                            }else{
                                String endDateC = tCourseOrderConfig.getEndTime().substring(0, 10);
                                if(endDateC.compareTo(endTime)<0){
                                    endDate = endDateC;
                                }else {
                                    endDate = endTime;
                                }

                            }
                            try {
                                Integer holiday = 0;
                                if(tCourseOrderConfig.getCirculateType() == 1){
                                    round = DateUtils.daysBetween(startDate, endDate)+1;
                                    stratD = startDate;
                                    endD = endDate;
                                    String sd = stratD;
                                    //查询假期
                                    String finalStratD = stratD;
                                    String finalEndD = endD;
                                    List<THoliday> tHolidaysE = tHolidayMapper.selectList(new QueryWrapper<THoliday>().eq("is_delete", 0).eq("state", 0).eq("org_id",tCourseOrderConfig.getOrgId()).and(qw->qw.between("start_date", finalStratD, finalEndD).or().between("end_date", finalStratD, finalEndD).or(qw1->qw1.le("start_date",finalStratD).ge("end_date",finalEndD))));
                                    if(!CollectionUtils.isEmpty(tHolidaysE)){
                                        for(THoliday tHoliday : tHolidaysE){
                                            if(DateUtils.getString(tHoliday.getStartDate(),"yyyy-MM-dd") .compareTo(sd)<=0&&DateUtils.getString(tHoliday.getEndDate(),"yyyy-MM-dd").compareTo(endD)>=0 ){
                                                holiday += DateUtils.daysBetween(sd ,endD) + 1;
                                            }else if(DateUtils.getString(tHoliday.getStartDate(),"yyyy-MM-dd") .compareTo(sd)>=0&&DateUtils.getString(tHoliday.getEndDate(),"yyyy-MM-dd").compareTo(endD)<=0 ){
                                                holiday += DateUtils.daysBetween(DateUtils.getString(tHoliday.getStartDate(),"yyyy-MM-dd") ,DateUtils.getString(tHoliday.getEndDate(),"yyyy-MM-dd"))+ 1;
                                            }else if(DateUtils.getString(tHoliday.getStartDate(),"yyyy-MM-dd") .compareTo(sd)<=0&&DateUtils.getString(tHoliday.getEndDate(),"yyyy-MM-dd").compareTo(endD)<=0 ){
                                                holiday += DateUtils.daysBetween(sd,DateUtils.getString(tHoliday.getEndDate(),"yyyy-MM-dd"))+ 1;
                                            }else if(DateUtils.getString(tHoliday.getStartDate(),"yyyy-MM-dd") .compareTo(sd)>=0&&DateUtils.getString(tHoliday.getEndDate(),"yyyy-MM-dd").compareTo(endD)>=0 ){
                                                holiday += DateUtils.daysBetween(DateUtils.getString(tHoliday.getStartDate(),"yyyy-MM-dd") ,endD)+ 1;
                                            }
                                        }
                                    }



                                }else{
                                    round = DateUtils.countWeekBetweenDates(     DateUtils.getLocalDate(startDate,"yyyy-MM-dd"),      DateUtils.getLocalDate(endDate,"yyyy-MM-dd"),tCourseOrderConfig.getWeekNum());
                                    stratD =  DateUtils.getLastDay(startDate, (tCourseOrderConfig.getWeekNum() - Integer.parseInt(DateUtils.weekNum(startDate)) + 7 ) % 7);
                                    endD = endDate;
                                    String sd = stratD;
                                    //查询假期

                                    String finalStratD = stratD;
                                    String finalEndD = endD;
                                    List<THoliday> tHolidaysE = tHolidayMapper.selectList(new QueryWrapper<THoliday>().eq("is_delete", 0).eq("state", 0).eq("org_id",tCourseOrderConfig.getOrgId())
                                            .and(qw->qw.between("start_date", finalStratD, finalEndD).or().between("end_date", finalStratD, finalEndD)
                                                    .or(qw1->qw1.le("start_date",finalStratD).ge("end_date",finalEndD))));
                                    if(!CollectionUtils.isEmpty(tHolidaysE)){
                                        for(THoliday tHoliday : tHolidaysE){
                                            if(DateUtils.getString(tHoliday.getStartDate(),"yyyy-MM-dd") .compareTo(sd)<=0&&DateUtils.getString(tHoliday.getEndDate(),"yyyy-MM-dd").compareTo(endD)>=0 ){
                                                holiday += DateUtils.countWeekBetweenDates(DateUtils.getLocalDate(sd,"yyyy-MM-dd"),DateUtils.getLocalDate(endD,"yyyy-MM-dd"),tCourseOrderConfig.getWeekNum());
                                            }else if(DateUtils.getString(tHoliday.getStartDate(),"yyyy-MM-dd") .compareTo(sd)>=0&&DateUtils.getString(tHoliday.getEndDate(),"yyyy-MM-dd").compareTo(endD)<=0 ){
                                                holiday += DateUtils.countWeekBetweenDates(tHoliday.getStartDate(),tHoliday.getEndDate(),tCourseOrderConfig.getWeekNum());
                                            }else if(DateUtils.getString(tHoliday.getStartDate(),"yyyy-MM-dd") .compareTo(sd)<=0&&DateUtils.getString(tHoliday.getEndDate(),"yyyy-MM-dd").compareTo(endD)<=0 ){
                                                holiday += DateUtils.countWeekBetweenDates(DateUtils.getLocalDate(sd,"yyyy-MM-dd"),tHoliday.getEndDate(),tCourseOrderConfig.getWeekNum());
                                            }else if(DateUtils.getString(tHoliday.getStartDate(),"yyyy-MM-dd") .compareTo(sd)>=0&&DateUtils.getString(tHoliday.getEndDate(),"yyyy-MM-dd").compareTo(endD)>=0 ){
                                                holiday += DateUtils.countWeekBetweenDates(tHoliday.getStartDate(),DateUtils.getLocalDate(endD,"yyyy-MM-dd"),tCourseOrderConfig.getWeekNum());
                                            }
                                        }
                                    }

                                }


                                round = round-holiday < 0 ? 0 : round-holiday;
                            } catch (ParseException e) {
                                throw new RuntimeException(e);
                            }
                        }

                    }
                }
                List<TStudentClassRela> tStudentClassRelas = tStudentClassRelaMapper.selectList(new QueryWrapper<TStudentClassRela>().eq("class_id", tCourseOrderConfig.getClassId()).eq("deleted", 0));
                Integer roundTemp = 0 ;
                if(!CollectionUtils.isEmpty(tStudentClassRelas)){
                    for (TStudentClassRela tStudentClassRela :tStudentClassRelas){
                        if(stratD.compareTo(DateUtils.getString(tStudentClassRela.getAddTime(),"yyyy-MM-dd") )>=0){
                            roundTemp = roundTemp + round  ;
                        }else{
                            try {
                                if(tCourseOrderConfig.getCirculateType() == 1){
                                    String sd = DateUtils.getString(tStudentClassRela.getAddTime(),"yyyy-MM-dd") ;
                                    int i = DateUtils.daysBetween(sd, endD) + 1 > 0 ? DateUtils.daysBetween(sd, endD) + 1 : 0;
                                    roundTemp = roundTemp + i >= round ?round:i ;
                                }else{
                                    String sd = DateUtils.getString(tStudentClassRela.getAddTime(),"yyyy-MM-dd") ;
                                    int i = DateUtils.countWeekBetweenDates(     DateUtils.getLocalDate(sd,"yyyy-MM-dd"),      DateUtils.getLocalDate(endD,"yyyy-MM-dd"),tCourseOrderConfig.getWeekNum()) > 0 ? DateUtils.countWeekBetweenDates(     DateUtils.getLocalDate(sd,"yyyy-MM-dd"),      DateUtils.getLocalDate(endD,"yyyy-MM-dd"),tCourseOrderConfig.getWeekNum())  : 0;
                                    roundTemp = roundTemp + i >= round ?round:i ;
                                }
                            } catch (ParseException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
                roundTotal += roundTemp;
                specifyNumber += roundTemp  * tCourseOrderConfig.getClassHour();
            }
        }else{
            map.put(studentAttendanceStr,new BigDecimal(0.0000));
            map.put(totalNumStr,new BigDecimal(0.0000));
        }

        if(0 == roundTotal){
            map.put(studentAttendanceStr,new BigDecimal(0.0000));
            map.put(totalNumStr,new BigDecimal(0.0000));
        }else{
            Map<String,Long> map1 = baseMapper.countP(dataTrendsVo,lastStartDate,endTime);
            BigDecimal studentAttendance = new BigDecimal(map1.get("num")) ;
            studentAttendance = studentAttendance.divide(new BigDecimal(roundTotal),4, RoundingMode.HALF_UP);
            map.put(studentAttendanceStr,studentAttendance);
            map.put(totalNumStr,roundTotal);
        }


        if(0 == specifyNumber){
            Map<String,BigDecimal> map1 = baseMapper.count(dataTrendsVo,lastStartDate,endTime);
            actualNumber =  map1.get("actualNumber");
            map.put(classHourStr,actualNumber);
            map.put(specifyNumberStr,specifyNumber);
            return new BigDecimal(0.0000F);
        }else {
            Map<String,BigDecimal> map1 = baseMapper.count(dataTrendsVo,lastStartDate,endTime);
            actualNumber =  map1.get("actualNumber");
        }
        //本年
        attendance = actualNumber.divide(new BigDecimal(specifyNumber),4, RoundingMode.HALF_UP);
        map.put(classHourStr,actualNumber);
        map.put(specifyNumberStr,specifyNumber);
        DecimalFormat decimalFormat = new DecimalFormat("0.####");
        decimalFormat.format(attendance);
        return attendance;
    }
}
